//****************************************************************************************
// Name:		proc.cpp
// Platform:	SQL Server 2000 SP3a or higher, Windows NT, 2000 or XP
// Author:		Copyright (c) 2006 by Michael Coles, MCDBA
//
// Description:	xp_create_local_key extended stored procedure
//
// LEGAL STUFF:
// ------------
// Copyright (C) 2005 - 2006 by Michael Coles, MCDBA
//
// Some included code included is released under the redistribution agreements as 
// specified by the authors of the respective code.  Copyright holders of this included 
// code maintain all copyright and other rights to their original or derivative works.
//
// All rights reserved.                          
//
// REDISTRIBUTION OF THIS CODE:
// ----------------------------
// All code included in this package is either the original work of the copyright holder,
// or derivative work based on other copyright holders' works.  All derivative works 
// include information as required by the copright holders' redistribution agreements.
// These redistribution agreements, where possible, are included in the text of the source
// code distributed with this code.
//
// Redistribution and use in source and binary forms, with or without modification, are 
// permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice, this list 
//      of conditions and the following disclaimer.
//
//   2. Redistributions in binary form must reproduce the above copyright notice, this 
//      list of conditions and the following disclaimer in the documentation and/or other 
//      materials provided with the distribution.
//
//   3. The names of its contributors may not be used to endorse or promote products 
//      derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT 
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY 
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//****************************************************************************************
#include <dblib.h>
#include <stdafx.h>
#include <constants.h>
#include <params.h>
#include <twister.h>
#include <sha2.h>
#include <aes.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_create_local_key(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_create_local_key(SRV_PROC *srvproc)
{
	RETCODE rc = XP_NOERROR;	// rc is the XP return code
	params *P1 = new params();	// master key
	params *P2 = new params();	// local key
	params *P3 = new params();	// password
	BYTE masterkey[64];// master key
	ULONG masterkeylength = 0;
	BYTE password[128];// password
	ULONG passwordlength = 0;	// password length
	BYTE localkey[64];	// local key
	ULONG localkeylength = 0;
	PBYTE pBuffer = new BYTE[128];
	ULONG dwSize = 0;
	ULONG len = 0;
	BYTE *output = new BYTE[128];
	int numparams = params::getparamcount(srvproc);
	try
	{
		if (numparams == 3) {
			params::getparam(srvproc, 3, P3);
			if (P3->isoutput) {
				Dblib::printerror(srvproc, USAGE_CREATE_LOCAL_KEY);
				rc = XP_ERROR;
			} else if (!P3->isnull) { // If parameter is not NULL, grab the third param
				srv_bzero(password, 128);
				memcpy(password, P3->cdata, P3->length);
				passwordlength = P3->length;
			} else { // If third parameter is NULL
				srv_bzero(password, 128);
				strcpy((char *)password, srv_pfield(srvproc, SRV_USER, (int *)NULL));
				strupr((char *)password);
				passwordlength = (int)strlen((char *)password);
			}
		} else { // Otherwise, with 2 params, grab the user name and use it to encrypt the key
			srv_bzero(password, 128);
			strcpy((char *)password, srv_pfield(srvproc, SRV_USER, (int *)NULL));
			strupr((char *)password);
			passwordlength = (int)strlen((char *)password);
		}
		if (rc == XP_NOERROR) {
			if (numparams >= 2) {
				params::getparam(srvproc, 1, P1);
				params::getparam(srvproc, 2, P2);
				if (P1->isoutput || !P2->isoutput || P2->maxlength < 64 || P1->length != 64) {
					Dblib::printerror(srvproc, USAGE_CREATE_LOCAL_KEY);
					rc = XP_ERROR;
				} else {
					srv_bzero(masterkey, 64);
					srv_bzero(localkey, 64);
					memcpy(masterkey, P1->cdata, P1->length);
					masterkeylength = P1->length;
				}
			} else {
				Dblib::printerror(srvproc, USAGE_CREATE_LOCAL_KEY);
				rc = XP_ERROR;
			}
		}
		if (rc == XP_NOERROR) {
			MTRand mtr;
			mtr.seed();
			for (int j = 0; j < 8; j++) {
				UINT32 i = mtr.randInt();
				localkey[j * 4] = (char)i >> 24;
				localkey[j * 4 + 1] = (char)(i >> 16) & 255;
				localkey[j * 4 + 2] = (char)(i >> 8) & 255;
				localkey[j * 4 + 3] = (char)(i & 255);
			}
			localkeylength = 64;
			sha512_ctx ctx[1];	// Create an SHA-512 hash
			sha512_begin(ctx);
			sha512_hash(localkey, localkeylength, ctx);
			sha512_end(localkey, ctx);

			BOOL bResult = false;
			HCRYPTPROV hProv = NULL;
			if(CryptAcquireContext(		// Grab a Crypto API Context
				&hProv,					// handle to the CSP
				SCRYPTO_KEY_CONTAINER,	// container name 
				NULL,					// use the default provider
				PROV_RSA_FULL,			// provider type
				CRYPT_MACHINE_KEYSET))	// flag values
			{
				//Dblib::printmessage(srvproc, "A new Crypto API cryptographic context acquired.");
			} else {
				Dblib::printerror(srvproc, "An MS Crypto API cryptographic service handle could not be acquired.");
				rc = XP_ERROR;
  			}
			if (rc == XP_NOERROR) {
				HCRYPTKEY hKey = NULL;
				HCRYPTHASH hHash = NULL;
				// Create a hash object.
				if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) {
					// Create a CryptoAPI hash object
					Dblib::printerror(srvproc, "Could not create a Crypto API Hash object.");
					rc = XP_ERROR;
				}
				if (rc == XP_NOERROR && !CryptHashData(hHash, (CONST BYTE *)password, passwordlength, 0)) {
					// Create a CryptoAPI hash of the password
					Dblib::printerror(srvproc, "Could not create SHA1 hash using Crypto API.");
					rc = XP_ERROR;
				}
				if (rc == XP_NOERROR && !CryptDeriveKey(hProv, CALG_RC4, hHash, 0, &hKey)) {
					// Derive a session key using the Crypto API
					Dblib::printerror(srvproc, "Could not derive a key using Crypto API.");
					rc = XP_ERROR;
				}
				if (rc == XP_NOERROR) {
					// Set variable to length of data in buffer.
					dwSize = 64;
					srv_bzero(pBuffer, 128);
					memcpy(pBuffer, masterkey, 64);
					// Now decrypt data.
					if (!CryptDecrypt(		// Perform the actual encryption
								hKey,			// Key obtained earlier
								0,				// No hashing of data
								TRUE,			// Final or only buffer of data
								0,              // Must be zero
								pBuffer,		// Data buffer
								&dwSize))
					{
						Dblib::printerror(srvproc, "Could not decrypt master key using Crypto API.");
						rc = XP_ERROR;
					}
					srv_bzero(output, 128);
					if (rc == XP_NOERROR) {
						// Encrypting
						Rijndael rin;
						rin.init(Rijndael::CBC, Rijndael::Encrypt, pBuffer, Rijndael::Key32Bytes);
						// It is a good idea to check the error code
						len = rin.padEncrypt(localkey, 64, output);
					}
					// Clean up
					CryptDestroyKey(hKey);
					CryptDestroyHash(hHash);
					CryptReleaseContext(hProv, 0);
					// Return the encrypted key
					srv_paramsetoutput (srvproc, 2, (BYTE *)output, (DBINT)len, false);
				}
			}
		}
	} catch(std::exception ex) {
		Dblib::printerror(srvproc, ERR_CRYPT_EXCEPTION);
		rc = XP_ERROR;
	}
	if (rc == XP_NOERROR) {
		srv_senddone(srvproc, (SRV_DONE_MORE), (DBSMALLINT)0, (DBINT)0);
	} else {
		srv_senddone(srvproc, (SRV_DONE_MORE | SRV_DONE_ERROR), (DBSMALLINT)0, (DBINT)0);
	}
	// Finished.  Clean up.
	if (pBuffer != NULL) {
		srv_bzero(pBuffer, 128);
		delete [] pBuffer;
	}
	delete [] output;
	output = NULL;
	pBuffer = NULL;
	srv_bzero(masterkey, 64);
	srv_bzero(localkey, 64);
	srv_bzero(password, 128);
	if (P1 != NULL)
		delete P1;
	P1 = NULL;
	if (P2 != NULL)
		delete P2;
	P2 = NULL;
	if (P3 != NULL)
		delete P3;
	P3 = NULL;
	return rc;
}